package org.client;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Iterator;
import java.util.Vector;

import org.model.ChatStrings;
import org.model.Friend;
import org.model.NetAddress;
import org.model.ViewUpdatable;

public class ChatServerConnector extends Thread
{
	private int mPort;
	private String mUsername;
	private DataOutputStream outputStream;
	private BufferedReader inputStream;
	private Socket clientSocket;
	private Vector<Friend> friends;
	private ViewUpdatable parent;
	private byte[] key;
	private String mPassword;
	

	public ChatServerConnector(String username, String password,int openPort, ViewUpdatable viewable) {
		mPort = openPort;
		mUsername = username;
		mPassword = password;
		friends = new Vector<Friend>();
		parent = viewable;
	}

	public boolean connect()
	{
		try {
			clientSocket = new Socket(InetAddress.getLocalHost(),1500);
			
			//-i modified here
			inputStream  = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
			//-sending the username.Ip,Port to the server
			outputStream = new DataOutputStream(clientSocket.getOutputStream());
			char[] privateKey = new char[1024];
			inputStream.read(privateKey);
			System.out.println((int)privateKey[0]);
			key = new byte[1024];
			for (int i = 0; i < privateKey.length; i++) 
				key[i] = (byte) privateKey[i];
			parent.setPrivateKey(key);
			//inputStream.setPrivateKey(key);
			//outputStream.setPrivateKey(key);
			//-
			
			outputStream.writeBytes(mUsername+ChatStrings.END_LINE);
			outputStream.writeBytes(mPassword+ChatStrings.END_LINE);
			
			String line = inputStream.readLine();
			if(!line.equals("1"))
				return false;
			
			byte[] address =InetAddress.getLocalHost().getAddress();
			System.out.println(address.toString());
			outputStream.write(address);
			outputStream.writeBytes(mPort+ChatStrings.END_LINE);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	@Override
	public void run() {
		super.run();
		try {			
			String line;
			while((line = inputStream.readLine()).compareTo("-1") != 0)
			{
				int port = Integer.parseInt(line);
				char[] rAddress = new char[4];
				inputStream.read(rAddress);
				String name = inputStream.readLine();
				friends.add(new Friend(name,new NetAddress(port,rAddress)));
			}
			
			refreshList();
		
			while(true)
			{
				line = inputStream.readLine();
				if(line.compareTo("in") == 0)
				{
					line = inputStream.readLine();
					int port = Integer.parseInt(line);
					char[] rAddress = new char[4];
					inputStream.read(rAddress);
					String name = inputStream.readLine();
					friends.add(new Friend(name,new NetAddress(port,rAddress)));
				}
				else
				{
					line = inputStream.readLine();
					Integer.parseInt(line);
					char[] rAddress = new char[4];
					inputStream.read(rAddress);
					String name = inputStream.readLine();
					Iterator<Friend> iter = friends.iterator();
					int  index = 0;
					int foundAt = -1;
					while (iter.hasNext()) {
						Friend friend = (Friend) iter.next();
						if(friend.getName().compareTo(name) == 0)
						{
							foundAt = index;
						}
						index++;
					}
					friends.removeElementAt(foundAt);
				}
				refreshList();
			}				
		} catch (Exception e) {
			//e.printStackTrace();
			System.err.println("Server is closed");
			//JOptionPane.showMessageDialog(null, "Server is Not opened");
			System.exit(0);
		}
		
	}
	private void refreshList()
	{
		parent.updateView(friends);
	}

	public void logOut() {
		try {
			outputStream.writeBytes("logOut"+mPort+ChatStrings.END_LINE);	
			outputStream.write(InetAddress.getLocalHost().getAddress());
			clientSocket.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
}